package cn.cxy.demo.viewmodel

import androidx.lifecycle.MutableLiveData
import cn.cxy.demo.base.BaseViewModel
import cn.cxy.demo.common.loadmore.LoadMoreStatus
import cn.cxy.demo.network.ArticleListRepo
import cn.cxy.demo.network.response.Article

class ArticleListViewModel : BaseViewModel() {

    private var page = INITIAL_PAGE
    private val articleListRepo by lazy { ArticleListRepo() }
    val articleList: MutableLiveData<MutableList<Article>> = MutableLiveData()
    val loadMoreStatus = MutableLiveData<LoadMoreStatus>()
    val refreshStatus = MutableLiveData<Boolean>()
    val reloadStatus = MutableLiveData<Boolean>()

    /**
     * @param onSuccess 主要执行代码块
     * @param onFailure 失败处理代码块
     * @param onComplete 无论是否异常都执行的代码块
     */
    fun loadArticleList() {
        refreshStatus.value = true
        reloadStatus.value = false
        launch(
                block = {
                    val pagination = articleListRepo.getArticleList(INITIAL_PAGE)
                    articleList.value = mutableListOf<Article>().apply { addAll(pagination.datas) }
                    page = pagination.curPage
                },
                onFailure = { reloadStatus.value = page == INITIAL_PAGE },
                onComplete = { refreshStatus.value = false }
        )
    }

    /**
     * 加载更多数据
     */
    fun loadMoreArticleList() {
        loadMoreStatus.value = LoadMoreStatus.LOADING
        launch(
                block = {
                    val pagination = articleListRepo.getArticleList(page)
                    page = pagination.curPage
                    val currentList = articleList.value ?: mutableListOf()
                    currentList.addAll(pagination.datas)
                    articleList.value = currentList
                    loadMoreStatus.value = if (pagination.offset >= pagination.total) {
                        LoadMoreStatus.END
                    } else {
                        LoadMoreStatus.COMPLETED
                    }
                },
                onFailure = { loadMoreStatus.value = LoadMoreStatus.ERROR }
        )
    }

    companion object {
        const val INITIAL_PAGE = 0
    }
}